package cmms.home.web.page;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import cmms.home.dao.PointSevice;
import cmms.home.vo.PointBO;
import cmms.home.vo.PointLogBO;
import cmms.utils.PlotUtils;
import fab.web.mvc.AbstractAction;
import fab.web.mvc.annotation.Action;
import fab.web.mvc.annotation.Bean;
import fab.web.mvc.annotation.Controller;
import fab.web.mvc.annotation.Param;
import fab.web.mvc.dao.IDao;
import fab.web.mvc.model.AbstractModel.Type;
import fab.web.mvc.model.JsonModel;
import fab.web.mvc.model.VelocityModel;

@Controller(value = "/frame/", validate = AbstractAction.VALIDATE_NONE)
public class Frame {
	private static final int POINT_MAX_INDEX = 23;
	@Bean
	private PointSevice pointService;
	
	public PointSevice getPointService() {
		return pointService;
	}

	public void setPointService(PointSevice pointService) {
		this.pointService = pointService;
	}

	@Action
	public void main(VelocityModel model, IDao dao) {
		PointBO[] points = pointService.LoadSortedPoints(dao, POINT_MAX_INDEX);
		
		model.put("points", points);
	}
	
	@Action
	public void status(VelocityModel model, IDao dao) {
		PointBO[] points = pointService.LoadSortedPoints(dao, POINT_MAX_INDEX);
		
		model.put("points", points);
	}
	
	@Action
	public void plot(VelocityModel model) {
	}
	
	@Action(Type.json)
	public void plot_data(JsonModel model, IDao dao, 
			@Param("index") int index, 
			@Param("startTime") Timestamp startTime,
			@Param("endTime") Timestamp endTime) {
		// 处理
		startTime = PlotUtils.adjustTime(startTime, 30);
		endTime = PlotUtils.adjustTime(endTime, 30, startTime, 6 * 60);
		
		List<PointLogBO> logs = pointService.listLog(dao, index, startTime, endTime);
		
		if (logs != null) {
			List<String> listX = new ArrayList<String>();
			List<String> listY = new ArrayList<String>();
			
			// 半小时一个刻度，选取时间附近的数据
			int logIndex = 0;
			for (long firstTime = startTime.getTime(); firstTime < endTime.getTime(); firstTime += 30 * 60000) {
				boolean find = false;
				
				for (int i = logIndex; i < logs.size(); i++) {
					PointLogBO bo = logs.get(i);
					
					int ret = (PlotUtils.betweenMintue(bo.getTime(), firstTime, 0, 30));
					
					if (ret >= 0) {
						if (ret == 0) {
							listX.add(bo.getDisplayX());
							listY.add(bo.getDisplayY());
							find = true;
						}
						
						logIndex = i;
						break;
					}
				}
				
				if(!find) {
					listX.add("-");
					listY.add("-");
				}
			}
			
//	        String[] x = new String[]{"2.0", "4.9", "7.0", "23.2", "25.6", "76.7", "135.6", "162.2", "32.6", "20.0", "6.4", "3.3"};
//	        double[] y = new double[]{2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3};
	
			model.put("x", listX);
			model.put("y", listY);
		} else {
			model.setErrorMessage("沒有數據");
		}
	}
}
